<template>
	<view>
		<u--form>

			<u-form-item label="信息" prop="userInfo.goodsDescription" borderBottom ref="item1">
				<u--textarea count maxlength=' 200' v-model="SocialInfo.content" placeholder="内容" autoHeight>
				</u--textarea>
			</u-form-item>
			<u-form-item labelWidth='40' label="分享图片" prop="userInfo.goodsImage" borderBottom ref="goodsimage">
				<u-upload :previewFullImage="true" :fileList="SocialInfo.image" @afterRead="afterRead"
					@delete="deletePic" name="1" multiple :maxCount="1">
				</u-upload>
			</u-form-item>
			<u-button @click="submit" class="submit" text="提交"
				color="linear-gradient(to right, rgb(66, 83, 216), rgb(213, 51, 186))">
			</u-button>
			<u-toast ref="uToast"></u-toast>

		</u--form>
	</view>
</template>

<script>
	import {
		addSocial
	} from '@/config/api.js'
	export default {
		data() {
			return {
				SocialInfo: {
					image: [{
						url: ''
					}],
					content: ''
				}

			}
		},
		methods: {
			submit() {
				console.log("进入上传动态方法");
				let name = '';
				let token = '';

				uni.getStorage({
					key: 'user_token',
					success: function(res) {
						token = res.data
					}
				})
				uni.getStorage({
					key: 'user_name',
					success: function(res) {
						name = res.data
					}
				})
				addSocial({
					socialBelongtoUser: name,
					socialContent: this.SocialInfo.content,
					socialImage: this.SocialInfo.image.url
				}, {
					params: {
						token: token
					}
				}).then((res) => {
					console.log(res);
				}).catch(e => {
					console.log(e);
				})
			},
			//删除图片
			deletePic(event) {
				this.SocialInfo.image.splice(event.index, 1)
			},

			//添加图片
			async afterRead(event) {
				let img = [].concat(event.file)
				let fileListen = this.SocialInfo.image.length
				img.map((item) => {
					this.SocialInfo.image.push({
						item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < img.length; i++) {
					const result = await this.uploadFilePromise(img[i].url)
					let item = this.SocialInfo.image[fileListen]
					this.SocialInfo.image.splice(fileListen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListen++
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: 'http://localhost:8080/upload/fileoss/upGoodsImage', // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						formData: {
							user: 'test'
						},
						success: (res) => {
							setTimeout(() => {
								resolve(res.data.data)
							}, 1000)
							let data = JSON.parse(res.data);
							console.log(data.data);
							console.log(data.data.url);
							this.SocialInfo.image.url = data.data.url
							console.log(this.SocialInfo.image.url)
						}
					});
				})
			}
		},
	}
</script>

<style>

</style>
